package cn.tedu.security.controller;

import cn.tedu.security.mapper.UserMapper;
import cn.tedu.security.pojo.dto.UserLoginDTO;
import cn.tedu.security.pojo.dto.UserRegDTO;
import cn.tedu.security.pojo.entity.User;
import cn.tedu.security.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class UserController {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        System.out.println("userRegDTO = " + userRegDTO);
        UserVO userVO = mapper.selectByUserName(userRegDTO.getUsername());
        if (userVO!=null){
            return 2;//代表用户名已存在!
        }
        User u = new User();
        BeanUtils.copyProperties(userRegDTO,u);//把dto里面已有的属性复制到实体类中
        u.setCreated(new Date());//给时间赋值
        String password = new BCryptPasswordEncoder().encode(userRegDTO.getPassword());
        u.setPassword(password);
        mapper.insert(u);
        return 1;
    }

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO){
        System.out.println("userLoginDTO = " + userLoginDTO);

//        Authentication authentication = new UsernamePasswordAuthenticationToken(
//                userLoginDTO.getUsername(), userLoginDTO.getPassword());
//        Authentication authenticationResult =  authenticationManager.authenticate(authentication);
//        SecurityContextHolder.getContext().setAuthentication(authenticationResult);

        Authentication authentication
                = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUsername(), userLoginDTO.getPassword());
        Authentication authenticateResult = authenticationManager.authenticate(authentication);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authenticateResult);

        return 1;
    }

}
